Detach Xend from terminal, courtesy of Horms <horms@verge.net.au>.
authoremellor@leeni.uk.xensource.com <emellor@leeni.uk.xensource.com>
Thu, 8 Dec 2005 16:17:53 +0000 (16:17 +0000)
committeremellor@leeni.uk.xensource.com <emellor@leeni.uk.xensource.com>
Thu, 8 Dec 2005 16:17:53 +0000 (16:17 +0000)
* For setsid to effectively detach a process from the terminal,
  the following needs to occur:

    fork ()   Return control to the shell
    setsid () New session with no controlling terminal
    fork ()   The session leader (parent) exits and thus
              the resulting child process can never regain the terminal

  This patch adds the second fork

* The call to self.daemonize(), which now forks, is moved to
  run before self.tracing(), as now that it actually disconnects
  from the terminal, and thus the prevailing process, the trace
  loses the processes created in self.run().

Signed-off-by: Ewan Mellor <ewan@xensource.com>
tools/python/xen/xend/server/SrvDaemon.py

index 499da92f2268987a3c5ac97ed4f8c4666334741a..ff0a4ca9be10d1ed8072b7feca542617acac73f9 100644 (file)
@@ -123,9 +123,18 @@ class Daemon:
 
     def daemonize(self):
         if not XEND_DAEMONIZE: return
         # Detach from TTY.
+
+        # Become the group leader (already a child process)
         os.setsid()
 
+        # Fork, this allows the group leader to exit,
+        # which means the child can never again regain control of the
+        # terminal
+        if self.fork_pid(XEND_PID_FILE):
+            self.exit()
         # Detach from standard file descriptors, and redirect them to
         # /dev/null or the log as appropriate.
         os.close(0)
@@ -164,7 +173,7 @@ class Daemon:
         # we can avoid a race condition during startup
         
         r,w = os.pipe()
-        if self.fork_pid(XEND_PID_FILE):
+        if os.fork():
             os.close(w)
             r = os.fdopen(r, 'r')
             try:
@@ -178,6 +187,7 @@ class Daemon:
         else:
             os.close(r)
             # Child
+            self.daemonize()
             self.tracing(trace)
             self.run(os.fdopen(w, 'w'))
 
@@ -274,7 +284,6 @@ class Daemon:
 
             relocate.listenRelocation()
             servers = SrvServer.create()
-            self.daemonize()
             servers.start(status)
         except Exception, ex:
             print >>sys.stderr, 'Exception starting xend:', ex